﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace PloobsEngine.Utils
{
    public delegate void SleepTimerCallback();    

    /// <summary>
    /// Timer that sleep for a period of time
    /// ITS NOT A NEW THREAD, 
    /// it just sleep and call the callback (inside the main loop) when the time is passed
    /// </summary>
    public class SleepTimer : IUpdateable
    {
        Timer timer;
        int interval;
        SleepTimerCallback tc;
        bool finished = false;

        public bool Finished
        {
            get {
                lock (this)
                {
                    return finished;
                }
            }
            set {
                lock (this)
                {
                    finished = value;
                }
            }
        }

            
        /// <summary>
        /// Wspera um tempo e chama uma funcao
        /// </summary>
        /// <param name="interval">milisegundos</param>
        public SleepTimer(EngineStuff engine, int interval, SleepTimerCallback callback)
            : base(engine)
        {
            this.Start();
            this.interval = interval;
            tc = callback;
            timer = new Timer( (obj) => Finished = true , null,0, interval);            
        }

        public override void Update(Microsoft.Xna.Framework.GameTime gameTime)
        {
            if (Finished == true)
            {
                tc();
                Finished = false;
            }
        }

        public void StopTimer()
        {
            this.Stop();
            timer.Dispose();
        }
        public void Restart()
        {
            Finished = false;
            timer.Change(interval, System.Threading.Timeout.Infinite);
        }
    }
}
